<?php

namespace tmcore\services\wechat;

use tmcore\exceptions\WeChatException;
use tmcore\services\HttpService;

/**
 * 微信开放平台服务类
 */
class WxOpService
{
    protected array $config;

    /**
     * 初始化
     */
    public function __construct()
    {
        $this->config = $this->getConfig();
    }

    /**
     * 获取配置
     * @return array
     * @throws WeChatException
     */
    protected function getConfig()
    {
        $config = WxConfigService::getOpConfig();
        if (empty($config['app_id']) || empty($config['secret'])) {
            throw new WeChatException('请先设置微信开放平台配置');
        }
        return $config;
    }

    /**
     * 获取网站应用登录地址
     * @param string $redirectUri
     * @param string $state
     * @return string
     */
    public function getCodeUrl($redirectUri, $state)
    {
        $url = 'https://open.weixin.qq.com/connect/qrconnect?';
        $url .= 'appid=' . $this->config['app_id'] . '&redirect_uri=' . urlEncode($redirectUri) . '&response_type=code&scope=snsapi_login';
        $url .= '&state=' . $state . '#wechat_redirect';
        return $url;
    }

    /**
     * 通过code获取微信信息
     * @param string $code
     * @return mixed
     * @throws WeChatException
     */
    public function getUserAuthByCode($code)
    {
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token';
        $url .= '?appid=' . $this->config['app_id'] . '&secret=' . $this->config['secret'] . '&code=' . $code;
        $url .= '&grant_type=authorization_code';
        $http = HttpService::getRequest($url);
        $request = json_decode($http, true);
        if(empty($request['access_token'])) throw new WeChatException($request['errmsg']??'获取微信信息失败');
        return $request;
    }

    /**
     * 获取授权用户信息
     * @param string $accessToken
     * @param string $openid
     * @return mixed
     * @throws WeChatException
     */
    public static function getUserInfoByAuth($accessToken, $openid)
    {
        $url = 'https://api.weixin.qq.com/sns/userinfo';
        $url .= '?access_token=' . $accessToken . '&openid=' . $openid;
        $http = HttpService::getRequest($url);
        $request = json_decode($http, true);
        if(empty($request['openid'])) throw new WeChatException($request['errmsg']??'获取微信用户失败');
        return $request;
    }
}